<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>菜单列表</title>
<script src="../../../../static/js/vue.js" th:src="@{/js/vue.js}"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="../../../../static/css/element.css" th:href="@{/css/element.css}">
<link rel="stylesheet" href="../../../../static/css/global.css" th:href="@{/css/global.css}" />
<link rel="stylesheet" href="../../../../static/css/main.css" th:href="@{/css/main.css}" />
<link rel="stylesheet" href="../../../../static/css/myelement.css" th:href="@{/css/myelement.css}" />
<!-- 引入组件库 -->
<script src="../../../../static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
<script src="../../../../static/js/element.js" th:src="@{/js/element.js}"></script>
<script src="../../../../static/js/jquery.nestable.js" th:src="@{/js/jquery.nestable.js}"></script>
</head>
<body>
	<div id="app" v-cloak>
		<div class="main-content">
			<!-- 页面头部 -->
			<div class="page-header">
				<h1 class="page-title"><span v-if="menuType==0">平台菜单</span><span v-if="menuType==1">商户菜单</span></h1>
				<div class="z-pop_question">
					<el-popover ref="popoverq" placement="bottom-start" width="400"
						trigger="hover">
					<p class="z-jiao">
						管理系统菜单,菜单可以有三级<br />
					</p>
					</el-popover>
					<i v-popover:popoverq class="el-icon-question"></i>
				</div>
				<div class="breadcrumb">
					<a href="javascript: top.location.reload();">首页</a><span>/</span>系统
				</div>
			</div>
			<!-- 页面头部 end -->

			<div class="list-content">
				<!--条件筛选-->
				<!-- 
				<div class="content_item_filter clearfix">
					<div class="input-select fl btn-radid_none">
						<div class="filter-form filter-form-one clearfix">
							<el-select v-model="conditions.type.value" clearable
								placeholder="菜单类型"> <el-option
								v-for="(item,index) in optionsState" :key="index"
								:label="item.text" :value="item.value"> </el-option> </el-select>
						</div>
						<div class="filter-operate">
							<el-tooltip class="item" content="查询" placement="bottom-start">
							<el-button icon="el-icon-search" @click="change"></el-button> </el-tooltip>
							<el-tooltip class="item" content="清空" placement="bottom-start">
							<el-button icon="el-extend-clean" @click="clearMenu"></el-button>
							</el-tooltip>
						</div>
					</div>
					<div class="filter-btn fr">
						<el-button type="primary" @click="showDailog('','')">新增菜单</el-button>
					</div>
				</div>
                -->
				<div class="main_cont">
				    <div class="content_item_filter clearfix">
	  	 				<div class="filter-btn">
	  	 					<el-button type="primary" @click="showDailog('','')">新增菜单</el-button>
	  	 				</div>
	 				</div>
					<div class="drag_tree">
						<div class="cf nestable-lists">
							<div class="dd" id="nestable">
								<ol class="dd-list">
									<li v-for="topMenu in menuList" class="dd-item">
										<div class="dd-handle">
											<p class="fl" v-cloak>{{ topMenu.name }}</p>
										</div>
										<div class="dd_option fr">
											<button @click="showDailog(topMenu.uuid,topMenu.type)">新建子菜单</button>
											<span>|</span>
											<button @click="editDailog(topMenu)">编辑</button>
											<span>|</span>
											<button @click="deleteMenu(topMenu.uuid)">删除</button>
										</div>
										<ol v-for="firstChilredMenu in topMenu.childrens"
											class="dd-list">
											<li class="dd-item">
												<div class="dd-handle">
													<p class="fl" v-cloak>{{ firstChilredMenu.name }}</p>
												</div>
												<div class="dd_option fr">
													<button
														@click="showDailog(firstChilredMenu.uuid,firstChilredMenu.type)">新建子菜单</button>
													<span>|</span>
													<button @click="editDailog(firstChilredMenu)">编辑</button>
													<span>|</span>
													<button @click="deleteMenu(firstChilredMenu.uuid)">删除</button>
												</div>
												<ol v-for="secendChilredMenu in firstChilredMenu.childrens"
													class="dd-list">
													<li class="dd-item" data-id="6">
														<div class="dd-handle">
															<p class="fl" v-cloak>{{ secendChilredMenu.name }}</p>
														</div>
														<div class="dd_option fr">
															<button @click="editDailog(secendChilredMenu)">编辑</button>
															<span>|</span>
															<button @click="deleteMenu(secendChilredMenu.uuid)">删除</button>
														</div>
													</li>
												</ol>
											</li>
										</ol>
									</li>
								</ol>
							</div>
						</div>
						<input type="hidden" id="nestable-output" />
					</div>
				</div>
			</div>
		</div>
		
		<el-dialog :title="openText" :visible.sync="dialogFormVisible" @open="open">
			<el-form ref="menu-form" :model="menu" :rules="rules" label-width="80px" class="demo-ruleForm">
			    <el-form-item hidden
						label="ID" prop="uuid"> <el-input
						v-model="menu.uuid"></el-input> 
				</el-form-item> 
				<el-form-item hidden label="parentId" prop="parentId"> 
				  <el-input v-model="menu.parentId"></el-input> 
				 </el-form-item>
				<el-form-item label="上级菜单">
					<el-select v-model="parentMenuName" ref="menu-select" placeholder="请选择上级菜单">
						<el-option :value="menu.parentId"
							style="height: auto; padding: 0;"> <el-tree
							:data="menuList" node-key="uuid" ref="menu-tree"
							:props="defaultProps" @node-click="handleNodeClick"></el-tree> </el-option>
					 </el-select>
				</el-form-item>
				<el-form-item label="菜单名称" prop="name">
					<el-input v-model="menu.name"></el-input>
				</el-form-item>
				<el-form-item label="菜单链接" prop="url"> 
					<el-input v-model="menu.url"></el-input> 
				</el-form-item>
				<el-form-item label="菜单图标">
					<div class="upload-image-box" @click="dialogImageVisible = true" style="width:70px;height:70px;">
						<div v-show="uploadImage.imageUrl" class="upload-image">
							<img :src="uploadImage.imageUrl">
							<!-- <span class="upload-operate">点击修改</span> -->
							<span class="upload-operate upload-operate-delect" @click.stop="handleRemove">点击删除</span>
						</div>
						<span v-show="!uploadImage.imageUrl" class="upload-button">
							<i class="el-icon-upload"></i>
							添加图片
						</span>
					</div>
				</el-form-item>
	
				<el-form-item label="类型" prop="type"> 
				   <el-radio-group v-model="menu.type"> 
					   <el-radio :label="0">平台菜单</el-radio>
					   <el-radio :label="1">商户菜单</el-radio> 
				   </el-radio-group> 
				</el-form-item>
				<el-form-item label="排序" prop="position"> 
				  <el-input v-model.number="menu.position"></el-input> 
				</el-form-item>
				<el-form-item label="是否启用" prop="specStatus"> 
		           <el-radio-group v-model="menu.state"> 
				   <el-radio :label=1>是</el-radio> 
				   <el-radio :label=0>否</el-radio>
		          </el-radio-group> 
		    </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" id="addDialog" style="display: none">
				<el-button @click="saveMenu" type="primary">确定</el-button>
				<el-button @click="dislogHide">取消</el-button>
			</div>
			<div slot="footer" class="dialog-footer" id="editDialog"
					style="display: none">
					<el-button @click="updateMenu" type="primary">确定</el-button>
					<el-button @click="dislogHide">取消</el-button>
			</div>
		</el-dialog>
		
		 <!-- 上传图片模态框 -->
		<el-dialog title="上传文件" :visible.sync="dialogImageVisible">
			<el-upload v-model="menu.icon"
			  ref="upload"
			  action="/fastdfs/file/uploadFile"
			  :multiple=false 
			  :limit="1"
			  list-type="picture"
			  :file-list="fileList"
			  :on-success="dosuccess"
			  :on-remove="handleRemove"
			  :before-upload="beforeAvatarUpload">
			  <el-button size="medium">+&nbsp;点击选择图片</el-button>
			  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
			    <el-button @click="dialogImageVisible = false">确 定</el-button>
			</div>
		</el-dialog>
        <!-- 上传图片模态框 end -->
	</div>

</body>
<script th:inline="javascript">
   //输入框 placeholder
	var zPlaceholder = {
		selects: function (ele) {
			var selects = document.querySelectorAll(ele); 
	  	for(var i = 0, len = selects.length; i < len; i++ ) {
	  		if(selects[i].__vue__.placeholder) {
	  			selects[i].children[0].children[0].placeholder = selects[i].__vue__.placeholder;
	  		}else {
	  			selects[i].children[0].children[0].placeholder = selects[i].children[0].attributes.placeholder.value;
	  		}

	  	}
		},
		inputs: function (ele) {
			var inputs = document.querySelectorAll(ele); 
	  	for(var j = 0, leng = inputs.length; j < leng; j++ ) {
	  		inputs[j].children[0].placeholder = inputs[j].attributes.placeholder.value;
	  	}
		}
	}
    new Vue({
        el: "#app",
        data: {
			dialogFormVisible: false,
			dialogImageVisible: false,  // 上传图片模态框是否显示
		    showChoice: false,
            optionsState: [{text:'平台菜单', value:'0'},{text:'商户菜单', value:'1'}],
            valueId: '',
            valueState: '',
            parentMenuName: '',
            fileName:"",
            openText:"新增菜单",
            operationType: '',
            uuid: '',
            menuObject: undefined,
            fileList:[],
            menuList: [[${topMenus}]],
            menuType:[[${menuType}]],
            conditions: {
                "type": {
                    "operation": "EQ",
                    "value": [[${menuType}]]
                } 
            }, 
            menu: {
            	name: '',
            	url: '',
            	icon: '',
            	type: '',
            	position: '',
            	parentId: '',
            	state: 1,
            },
	        // 上传图片数据
	        uploadImage: {
	        	imageUrl: '',
	        	fileList: []
	        },
            rules: {
            	name: [
                           {required: true, message: "请输入菜单名称", trigger: 'blur'},
                           {max: 20, message: '菜单名称不能超过20个字符', trigger: 'blur' }
                       ],
                url: [{max: 200, message: '菜单链接不能超过200个字符', trigger: 'blur' }],
                type: [{required: true, message: "请选择菜单类型", trigger: 'change'}],
                position:[{ type: 'number', message: '显示顺序必须为数值',trigger: 'blur'}]
            },
            defaultProps: {
                id: 'uuid',
                label: 'name',
                children: 'childrens'
            },
        },
        methods: {
        	 beforeAvatarUpload(file) {
       	        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
       	        const isLt2M = file.size / 1024 / 1024 < 1;

       	        if (!isJPG) {
       	        	this.$message({
                     message: '菜单图标只能是 JPG、PNG 格式!',
                     type: 'error',
                     customClass: 'message-center',
                   });
       	        }
       	        if (!isLt2M) {
       	        	this.$message({
                        message: '菜单图标大小不能超过 1MB!',
                        type: 'error',
                        customClass: 'message-center',
                      });
       	        }
       	        return isJPG && isLt2M;
       	      },
        	dosuccess:function(response, file, fileList){
        		this.menu.icon = response.fdfsIpPre + response.fullPath;
        		this.fileName = file.name;
        		this.uploadImage.imageUrl = response.fdfsIpPre + response.fullPath;
        	},
        	handleRemove:function(file, fileList){
        	var self = this;
   			 $.post("/fastdfs/file/deleteFile",
				    	{"fullPath":this.menu.icon},
					    function(data) {	
				    		var obj = eval('(' + data + ')');
							if(obj.returnCode){
								self.menu.icon = "";
								self.uploadImage.imageUrl = "";
								self.fileList=[];
				            }
					    }
					);
        	},
        	change: function (ele) {
        		window.location.href="/backstage/permission/menu/tolist?menuType="+this.conditions.type.value;
            },
            clearMenu: function(){
            	this.conditions.type.value = "";
            },
            handleSizeChange: function (val) {
                this.pageSize = val;
                this.queryManager();
            },
            handleNodeClick: function (data) {
                this.parentMenuName = data.name;
                this.menu.parentId = data.uuid;
                this.$refs['menu-select'].blur();
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.queryManager();
            },
            handleCurrentTable: function (val) {
                window.location.href = 'edit.html?no=' + val.no;
            },
            saveMenu: function () {
	            var self = this;
	            self.$refs['menu-form'].validate((valid) => {
	                if (valid) {
	                    $.ajax({
	                        url: "/backstage/permission/menu/add",
	                        type: "POST",
	                        data: JSON.stringify(self.menu),
	                        contentType: "application/json;charset=UTF-8",
	                        dataType: "json",
	                        success: function(data) {
	                            if (data && data.returnCode == "1") {
                                    self.$message({
                                        message: '新增菜单成功',
                                        type: 'success',
                                        duration: 1500,
                                        customClass: 'message-center',
                                        onClose: function () {
                                            window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
                                        }
                                    });
	                            } else {
	                                self.$message({
	                                        message: '新增菜单失败',
	                                        type: 'success',
	                                        customClass: 'message-center',
	                                        duration: 1500,
	                                        onClose: function () {
	                                            window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
	                                        }
	                                    });
	                            }
	                        }
	                    });
	                }
	            });
	        },
	        updateMenu: function () {
	            var self = this;
	            self.$refs['menu-form'].validate((valid) => {
	                if (valid) {
	                    $.ajax({
	                        url: "/backstage/permission/menu/edit",
	                        type: "POST",
	                        data: JSON.stringify(self.menu),
	                        contentType: "application/json;charset=UTF-8",
	                        dataType: "json",
	                        success: function(data) {
	                            if (data && data.returnCode == "1") {
                                    self.$message({
                                        message: '编辑菜单成功',
                                        type: 'success',
                                        customClass: 'message-center',
                                        duration: 1500,
                                        onClose: function () {
                                            window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
                                        }
                                    });
	                            } else {
                                    self.$message({
                                        message: '编辑菜单失败',
                                        type: 'success',
                                        customClass: 'message-center',
                                        duration: 1500,
                                        onClose: function () {
                                            window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
                                        }
                                    });
	                            }
	                        }
	                    });
	                }
	            });
	        },
	        deleteMenu(uuid) {
                var self = this;
                self.$confirm('确认要删除菜单?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                $.ajax({
                    url: "/backstage/permission/menu/delete",
                    type: "POST",
                    data: JSON.stringify([uuid]),
                    contentType: "application/json;charset=UTF-8",
                    dataType: "json",
                    success: function (data) {
                        if (data && data.returnCode == "1") {
                            self.$message({
                                message: '删除成功',
                                type: 'success',
                                customClass: 'message-center',
                                duration: 1500,
                                onClose: function () {
                                    window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
                                }
                            });
                        } else {
                            self.$message({
                                message: '删除失败',
                                type: 'success',
                                customClass: 'message-center',
                                duration: 1500,
                                onClose: function () {
                                    window.location.href = '/backstage/permission/menu/tolist?menuType='+self.conditions.type.value;
                                }
                            });
                        }
                    }
                });
                });
            },
            
  	      dislogHide: function () {
  	      	this.dialogFormVisible = false;
  	      },
  	      open:function(){
  	    	this.$nextTick(function () {
	    		// DOM 更新了
	    		console.log(this.$refs['menu-tree']);
	    		var type = this.operationType;
	    		if ("create" == type) {
	    			//根据父节点id找到父节点
	    			var createUuid = this.uuid;
	      	    	if (createUuid != "") {
	      	    		var parentNode = this.$refs['menu-tree'].getNode(createUuid);
	      	           	if (parentNode != null) {
	      	           		 this.parentMenuName = parentNode.data.name;
	      	           	}else {
	      	           		this.parentMenuName = '';
	      	           	}
	      	    	}else {
	      	    		this.parentMenuName = '';
	      	    	}
	    		}else {
	                //根据父节点id找到父节点
	                var object = this.menuObject;
	                if (object.parentId != null && object.parentId != '') {
	                	var parentNode = this.$refs['menu-tree'].getNode(object.parentId);
	                    this.parentMenuName = parentNode.data.name;
	                    this.menu.parentId = object.parentId;
	                }else {
	                	this.menu.parentId = '';
	                	this.parentMenuName = '';
	                }
	    		}
	    		
		  	});
  	    	
  	      },
  	      showDailog: function (uuid,type) {
  	    	this.dialogFormVisible = true;
  	    	this.fileList = [];
  	    	this.uploadImage.imageUrl = "";
  	    	this.openText = "新增菜单";
  	    	$("#addDialog").css('display','block'); 
  	    	$("#editDialog").css('display','none'); 
  	    	this.menu.parentId = uuid;
  	    	this.operationType = "create";
  	    	this.uuid = uuid;
  	    	if (type == "") {
  	    		this.menu.type = 0;
  	    	} else {
  	    		this.menu.type = type;
  	    	}
         	this.menu.uuid = '';
          	this.menu.name = '';
          	this.menu.url = '';
          	this.menu.icon = '';
          	this.menu.position = '';
          	this.menu.state = 1;
  	      	this.dialogFormVisible = true;
  	        $("#uploadButton").show();
  	      },
          editDailog: function(object){
        	this.dialogFormVisible = true;
        	this.openText = "编辑菜单";
        	this.operationType = "update";
  	    	$("#addDialog").css('display','none'); 
  	    	$("#editDialog").css('display','block'); 
  	    	this.menuObject = object;
          	this.menu.uuid = object.uuid;
          	this.menu.name = object.name;

          	this.menu.url = object.url;
          	this.menu.icon = object.icon;
          	this.menu.type = object.type;
          	this.menu.state = (object.state == true)?1:0;
          	this.menu.position = parseInt(object.position);
  	      	
  	        //如果菜单有图标，则显示并隐藏上传图标
            if (object.icon != "") {
            	this.fileList = [{name:this.menu.name,url:""+this.menu.icon+""}];
            	this.uploadImage.imageUrl = this.menu.icon;
            }else {
            	this.fileList = [];
            	this.uploadImage.imageUrl = "";
            }
  	    
          },
  	      hideChoice: function () {
  	      	this.showChoice = false;
  	      }
        },
        mounted: function () {
        	var _this = this;
		  	$('.z-tabs_item').click(function () {
		  		$(this).addClass('is_active').siblings().removeClass('is_active');
		  		var inx = $(this).index();
		  		
		  		$('.content_item').eq(inx).addClass('active').siblings().removeClass('active');
		  		
		  		if($('.content_item.active .right_pos table').length > 0) {
	  			var tableH = $('.right_pos').height();
	  			$('.right_table').height(tableH);
	  		}
		  	});
		  	
		  	//placeholder
		  	zPlaceholder.selects('.z_select-holder');
		  	zPlaceholder.inputs('.z_input-holder');
		  	
            //拖拽
		 	var updateOutput = function(e){
		        var list   = e.length ? e : $(e.target),
		            output = list.data('output');
		        if (window.JSON) {
		            output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));
		        } else {
		            output.val('JSON browser support required for this demo.');
		        }
		        $('.dragbtn').parent('li').addClass("on");
		       	$('.dd-item.on').each(function (i,v) {
		       		if($(v).children('a').hasClass('dragbtn')) {
		       		}else {
		       			$(v).removeClass('on');
		       		}
		       	});
		       	//拖拽返回值
		       	console.log($('#nestable-output').val());
		    };
		    
		  	
	  	    $('#nestable').nestable({
		        group: 1
		    }).on('change', updateOutput);
		    
		    updateOutput($('#nestable').data('output', $('#nestable-output')));
		    
		    $('#nestable').nestable('collapseAll');//折叠所有节点 
        },
       updated: function () {
   
		},
    });
</script>
</html>